#include "drv_l1_sfr.h"
#include "drv_l1_tft2.h"
#include "drv_l1_gpio.h"
#include "drv_l2_display.h"
#include "drv_l1_timer.h"
#include "drv_l1_uart.h"

#if LCD_DRV_EN_AUO_A027DTN019

static void auo_gpio_init(void)
{
	#if 0
	gpio_init_io(PANEL_IO_CSN, GPIO_OUTPUT);
	gpio_set_port_attribute(PANEL_IO_CSN, ATTRIBUTE_HIGH);

	gpio_init_io(PANEL_IO_SDA, GPIO_OUTPUT);
	gpio_set_port_attribute(PANEL_IO_SDA, ATTRIBUTE_HIGH);

	gpio_init_io(PANEL_IO_SCL, GPIO_OUTPUT);
	gpio_set_port_attribute(PANEL_IO_SCL, ATTRIBUTE_HIGH);
	#endif
}

static void cmd_delay(INT32U i)
{
	INT32U cnt,j;
	cnt = i*2;
	for (j=0;j<cnt;j++);
}
#define PANEL_IO_CSN IO_F15
#define PANEL_IO_SCL IO_F15
#define PANEL_IO_SDA IO_F15
static void serial_cmd_1(INT32U cmd)
{
	INT32S i;

	gpio_write_io(PANEL_IO_CSN, 1);//CS=1
	gpio_write_io(PANEL_IO_SCL, 0);//SCL=0
	gpio_write_io(PANEL_IO_SDA, 0);//SDA

	// set csn low
	gpio_write_io(PANEL_IO_CSN, 0);//CS=0
	cmd_delay(1);
	for (i=0;i<16;i++) {
		// shift data
		gpio_write_io(PANEL_IO_SDA, ((cmd&0x8000)>>15)); /* SDA */
		cmd = (cmd<<1);
		cmd_delay(1);
		// toggle clock
		gpio_write_io(PANEL_IO_SCL, 1);//SCL=0
		cmd_delay(1);
		gpio_write_io(PANEL_IO_SCL, 0);//SCL=0
		cmd_delay(1);
	}

	// set csn high
	gpio_write_io(PANEL_IO_CSN,1);//CS=1
	cmd_delay(1);

}

const INT8U AUO_REGTable[]={


	0x05,0x44,
	0x05,0x04,
	0x05,0x44,

	0x01,0xb4,//ups 052 mode
    0x00,0x23,
	0x04,0x1b,

	0x05,0x45,
//	0x05,0x5d,
//	0x85,0x80,
	0XFF,0XFF
};
static INT32S tft_auo_a027dtn019_init(void)
{
	INT8U i = 0;

	DBG_PRINT("%s\r\n", __func__);

	auo_gpio_init();

    while(AUO_REGTable[i] !=0xff)
    {
	    serial_cmd_1( (AUO_REGTable[i]<<8) |(AUO_REGTable[i+1]) );
    	i+=2;
    }

	R_TFT2_HS_WIDTH			= 1;				//	1		=HPW
	R_TFT2_H_START			= 1+240;			//	240		=HPW+HBP
	R_TFT2_H_END				= 1+240+1280;		//	1520	=HPW+HBP+HDE
	R_TFT2_H_PERIOD			= 1560;            	//	1560	=HPW+HBP+HDE+HFP
	R_TFT2_VS_WIDTH			= 1;				//	1		=VPW				(DCLK)
	R_TFT2_V_START			= 21;				//	21		=VPW+VBP			(LINE)
	R_TFT2_V_END				= 21+240;			//	261		=VPW+VBP+VDE		(LINE)
	R_TFT2_V_PERIOD			= 1+21+240;			//	262		=VPW+VBP+VDE+VFP	(LINE)
	R_TFT2_LINE_RGB_ORDER    = 0x00;

	drv_l1_tft2_signal_inv_set(TFT_VSYNC_INV|TFT_HSYNC_INV, (TFT_ENABLE & TFT_VSYNC_INV)|(TFT_ENABLE & TFT_HSYNC_INV));
	drv_l1_tft2_mode_set(TFT_MODE_UPS052);
	drv_l1_tft2_data_mode_set(TFT_DATA_MODE_8);
	drv_l1_tft2_clk_set(TFT_CLK_DIVIDE_8);	/* FS=66 */
	drv_l1_tft2_TFT_IO_enable(TRUE);
	drv_l1_tft2_en_set(TRUE);

	return STATUS_OK;
}

// tft table
const DispCtrl_t TFT_Param_auo_a027dtn019 =
{
	/* lcd size */
	320,
	240,
	/* display position */
	0, //pos_x
	0, //pos_y 
	/* pip size */
	128,
	96,
	/* pip position */
	-128,	//x
	0,	//y
	/* lcd init & uninit */
	tft_auo_a027dtn019_init,
	NULL,
	/* lcd backlight control */
	LCD_BL_CTRL_CONSTANT,
	20 * 1000,	// in HZ for LCD_BL_CTRL_PWM
	55,			// in duty cycle for LCD_BL_CTRL_PWM
	/* tft format */
	DISP_FMT_GP420
};
#endif
